//does each collection have an associated template?
mahees.backbone.Router.PageRouter = Backbone.Router.extend({
	routes : {
		'' : 'list',
		':id' : 'editPerson'
	},

	initialize : function(options) {
		_.bindAll(this, 'editPerson', 'savePersonData', 'list', 'navigatePersonView');

		this.eventBus = new mahees.backbone.EventBus();
		this.eventBus.bind('saveModel', this.savePersonData);
		this.eventBus.bind('personSelected', this.navigatePersonView);

		this.personModel = new mahees.backbone.Model.PersonModel();
		this.personModel.bind('change:emergencyContacts', function(model, emergencyContactsJSONArray) {
			_.each(model.get('emergencyContacts'), function(emergencyContactJSONObject) {
				mahees.backbone.Utility.ConvertArrayToCollection(emergencyContactJSONObject, 'phones', mahees.backbone.Collection.PhoneCollection)
			});

			mahees.backbone.Utility.ResetCollection(model, 'emergencyContacts');
		});

		this.personCollection = new mahees.backbone.Collection.PersonCollection();

	},

	savePersonData : function() {
		this.personModel.save({}, {
			success : function(model, resp) {
				console.log(JSON.stringify(model.toJSON()));
			},
			error : function() {
				console.log('server broke on save');
			}
		});
	},

	navigatePersonView : function(model) {
		this.navigate('' + model.id, true);
	},

	editPerson : function(id) {
		var self = this;

		this.personProfileView = new mahees.backbone.View.PersonProfileView({
			model : this.personModel,
			eventBus : this.eventBus
		});
		$('#main').html(this.personProfileView.render().el)

		this.personModel.id = id;
		this.personModel.fetch({
			error : function() {
				alert('unable to fetch resourse');
				console.log('server broke did not fetch')
				self.navigate('', true);
			}
		});
	},

	list : function() {
		this.personProfileListView = new mahees.backbone.View.PersonProfileListView({
			collection : this.personCollection,
			eventBus : this.eventBus
		});

		this.personCollection.fetch();

		$('#main').html(this.personProfileListView.render().el)
	}

});

// Collections
mahees.backbone.Collection.PersonCollection = Backbone.Collection.extend({
	model : mahees.backbone.Model.PersonModel,

	url : '../rest/persons'
});

mahees.backbone.Collection.PhoneCollection = Backbone.Collection.extend({
	model : mahees.backbone.Model.PhoneModel
});

mahees.backbone.Collection.EmergencyContactCollection = Backbone.Collection.extend({
	model : mahees.backbone.Model.EmergencyContactModel
});
// END Collections

// Models
mahees.backbone.Model.PersonModel = Backbone.Model.extend({
	url : function() {
		var base = '../rest/person';
		if (this.isNew())
			return base;
		return base + (base.charAt(base.length - 1) == '/' ? '' : '/') + this.id;
	},

	defaults : {
		firstName : '',
		lastName : '',
		emergencyContacts : new mahees.backbone.Collection.EmergencyContactCollection()
	},

	initialize : function() {
		this.validator = mahees.backbone.Utility.Validator();
	},

	validate : function(attrs) {
		if (attrs.firstName != undefined && (attrs.firstName == '')) {
			return {
				name : 'firstName',
				message : 'cant be blank'
			};
		}

		if (attrs.lastName != undefined && (attrs.lastName == '')) {
			return {
				name : 'lastName',
				message : 'cant be blank'
			};
		}
	}

});

mahees.backbone.Model.PhoneModel = Backbone.Model.extend({
	defaults : {
		phone : '',
		phoneType : ''
	},

	initialize : function() {
		_.bindAll(this, 'validate');

		this.validator = mahees.backbone.Utility.Validator();
	},

	validate : function(attrs) {
		if (attrs.phone != undefined && (!this.validator.phone(attrs.phone))) {
			return {
				name : 'phone',
				message : '10 digits'
			}
		}

		if (attrs.phoneType != undefined && (attrs.phoneType == '')) {
			return {
				name : 'phoneType',
				message : 'cant be blank'
			};
		}
	}

});

mahees.backbone.Model.EmergencyContactModel = Backbone.Model.extend({
	defaults : {
		firstName : '',
		lastName : '',
		mainContact : false,
		phones : new mahees.backbone.Collection.PhoneCollection()
	},

	initialize : function() {
		this.validator = mahees.backbone.Utility.Validator();
	},

	validate : function(attrs) {
		if (attrs.firstName != undefined && (attrs.firstName == '')) {
			return {
				name : 'firstName',
				message : 'cant be blank'
			};
		}

		if (attrs.lastName != undefined && (attrs.lastName == '')) {
			return {
				name : 'lastName',
				message : 'cant be blank'
			};
		}
	}

});
// END Models

// Views
mahees.backbone.View.PersonProfileSimpleView = mahees.backbone.View.BasicView.extend({

	viewIdentifier : 'personProfileSimple',

	customInitialize : function() {
		_.bindAll(this, 'viewPerson');
	},

	events : {
		'click a.personProfileSimple.viewPerson' : 'viewPerson',
	},

	viewPerson : function() {
		this.options.eventBus.trigger('personSelected', this.model);
		return false;
	}
});

mahees.backbone.View.PersonProfileView = mahees.backbone.View.BasicView.extend({

	viewIdentifier : 'personProfile',

	events : {
		'click span.personProfile.addEmergencyContact' : 'addEmergencyContact',
		'click button#saveProfile.personProfile' : 'saveProfile',
		'change input.personProfile' : 'updateModel',
		'click button#print.personProfile' : 'printProfile',
	},

	printProfile : function() {
		var mywindow = window.open('printPage/' + this.model.id, 'EmailPreview', 'height=400,width=600');

		// mywindow.document.write(
		// window.document.getElementById('emailBody').innerHTML );

		// mywindow.document.close();
		mywindow.focus();
		// mywindow.print();
		// mywindow.close();
	},

	customInitialize : function() {
		_.bindAll(this, 'addEmergencyContact', 'saveProfile', 'printProfile');

		this.emergencyContacts = this.model.get('emergencyContacts')
		this.emergencyContactListView = new mahees.backbone.View.EmergencyContactListView({
			collection : this.emergencyContacts
		});
	},

	saveProfile : function() {
		this.options.eventBus.trigger('saveModel');
	},

	customRender : function() {
		$(this.el).append(this.emergencyContactListView.render().el);
	},

	addEmergencyContact : function() {
		var item = new mahees.backbone.Model.EmergencyContactModel();
		this.emergencyContacts.add(item);
	},
});

mahees.backbone.View.EmergencyContactView = mahees.backbone.View.BasicView.extend({
	tagName : 'p',

	viewIdentifier : 'emergencyContact',

	events : {
		'click span.emergencyContact.delete' : 'remove',
		'click button.emergencyContact.addPhone' : 'addPhone',
		'change input.emergencyContact' : 'updateModel'
	},

	customInitialize : function() {
		_.bindAll(this, 'addPhone');

		this.phones = this.model.get('phones');
		this.phoneListView = new mahees.backbone.View.PhoneListView({
			collection : this.phones
		});
	},

	customRender : function() {
		$(this.el).append(this.phoneListView.render().el)
	},

	addPhone : function() {
		var item = new mahees.backbone.Model.PhoneModel();
		this.phones.add(item);
	},

});

mahees.backbone.View.PhoneView = mahees.backbone.View.BasicView.extend({
	viewIdentifier : 'phone',

	events : {
		'click span.phone.delete' : 'remove',
		'change input.phone' : 'updateModel',
		'change select.phone' : 'updateModel'
	},

	customRender : function() {
		mahees.backbone.Utility.SelectItem(this.model, 'phoneType', this.el);
	}

});

// Collection Views
mahees.backbone.View.EmergencyContactListView = mahees.backbone.View.BasicListView.extend({
	refModelView : mahees.backbone.View.EmergencyContactView
});

mahees.backbone.View.PhoneListView = mahees.backbone.View.BasicListView.extend({
	refModelView : mahees.backbone.View.PhoneView
});

mahees.backbone.View.PersonProfileListView = mahees.backbone.View.BasicListView.extend({
	refModelView : mahees.backbone.View.PersonProfileSimpleView
});

// Collection Views END
